﻿using System;
using System.Data;
using System.Globalization;
using System.Web.UI.WebControls;
using Pantry.Business;
using Pantry.Commons;

namespace Pantry.Web.Users.Controls
{
    public partial class ListDirectorates : System.Web.UI.UserControl
    {
        #region Private Members

        private readonly IFormatProvider _formatProvider = CultureInfo.CurrentCulture;
        private DirectorateBus _directorateBus;
        private DataView _dataView;
        private static bool _isSorted = true;

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            RemoveActiveOnButton();
            LinkButton1.CssClass = "button-active";
            if (Request.QueryString["id"] != null)
            {
                InitialData(CheckBoxIncludeInactive.Checked);
            }
            
        }
        #region Support Methods

        /// <summary>
        /// Filters the directorates.
        /// </summary>
        /// <param name="isIncludeInActive">if set to <c>true</c> [is include in active].</param>
        /// <param name="filterString">The filter string.</param>
        private void FilterDirectorates(bool isIncludeInActive, string filterString)
        {
            try
            {
                if (Request.QueryString["id"] != null)
                {
                    int organizationId = int.Parse(Request.QueryString["id"], _formatProvider);
                    _directorateBus = new DirectorateBus();
                    DataTable dataTable = _directorateBus.ListAllDirectorates(organizationId);
                    _dataView = dataTable.DefaultView;
                    string filterStatement = "";
                    if (filterString.Length > -1)
                    {
                        for (var i = 0; i < filterString.Length; i++)
                        {
                            if (i == (filterString.Length - 1))
                            {
                                if (!isIncludeInActive)
                                {
                                    filterStatement += "DirectorateName LIKE '" + filterString.Substring(i - 1, 1) +
                                                       "*') AND Status = 'Yes'";
                                }
                                else
                                {
                                    filterStatement += "DirectorateName LIKE '" + filterString.Substring(i - 1, 1) +
                                                       "*')";
                                }
                            }
                            else if (i == 0)
                            {
                                filterStatement += "(";
                            }
                            else
                            {
                                filterStatement += "DirectorateName LIKE '" + filterString.Substring(i - 1, 1) +
                                                   "*' OR ";
                            }
                        }
                        _dataView.RowFilter = filterStatement;
                    }
                    CollectionPager1.PageSize = 10;
                    CollectionPager1.BindToControl = RepeaterDirectorate;
                    CollectionPager1.DataSource = _dataView;
                    RepeaterDirectorate.DataSource = CollectionPager1.DataSourcePaged;
                    RepeaterDirectorate.DataBind();
                }

            }
            catch (ApplicationException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
        }
        /// <summary>
        /// Initials the data.
        /// </summary>
        /// <param name="isIncludeInActive">if set to <c>true</c> [is include in active].</param>
        private void InitialData(bool isIncludeInActive)
        {

            try
            {
                int organizationId = int.Parse(Request.QueryString["id"], _formatProvider);
                _directorateBus = new DirectorateBus();
                DataTable dataTable = _directorateBus.ListAllDirectorates(organizationId);
                _dataView = dataTable.DefaultView;
                if (!isIncludeInActive)
                {
                    _dataView.RowFilter = "Status = 'Yes'";
                }
                CollectionPager1.PageSize = 10;
                CollectionPager1.BindToControl = RepeaterDirectorate;
                CollectionPager1.DataSource = _dataView;
                RepeaterDirectorate.DataSource = CollectionPager1.DataSourcePaged;
                RepeaterDirectorate.DataBind();

            }
            catch (FormatException ex)
            {
                ExceptionHandler.WriteErrorLog(ex);
                Response.Write(ex.Message);
            }
        }

        /// <summary>
        /// Sortings the specified field.
        /// </summary>
        /// <param name="field">The field.</param>
        private void Sorting(string field)
        {
            try
            {
                if (_isSorted)
                {
                    _dataView.Sort = string.Format(_formatProvider, "{0} DESC", field);
                    _isSorted = false;
                }
                else
                {
                    _dataView.Sort = string.Format(_formatProvider, "{0} ASC", field);
                    _isSorted = true;
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
        }
        #endregion

        #region Event Handler

        /// <summary>
        /// Checks the box include in active changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void CheckBoxIncludeInactiveChanged(object sender, EventArgs eventArgs)
        {
            InitialData(CheckBoxIncludeInactive.Checked);
        }
        /// <summary>
        /// Links the button1 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton1Click(object sender, EventArgs e)
        {
            InitialData(CheckBoxIncludeInactive.Checked);
            RemoveActiveOnButton();
            LinkButton1.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button2 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton2Click(object sender, EventArgs e)
        {
            FilterDirectorates(CheckBoxIncludeInactive.Checked, "0123456789");
            RemoveActiveOnButton();
            LinkButton2.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button3 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton3Click(object sender, EventArgs e)
        {
            FilterDirectorates(CheckBoxIncludeInactive.Checked, "ABCDE");
            RemoveActiveOnButton();
            LinkButton3.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button4 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton4Click(object sender, EventArgs e)
        {
            FilterDirectorates(CheckBoxIncludeInactive.Checked, "FGHIJ");
            RemoveActiveOnButton();
            LinkButton4.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button5 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton5Click(object sender, EventArgs e)
        {
            FilterDirectorates(CheckBoxIncludeInactive.Checked, "KLMN");
            RemoveActiveOnButton();
            LinkButton5.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button6 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton6Click(object sender, EventArgs e)
        {
            FilterDirectorates(CheckBoxIncludeInactive.Checked, "OPQR");
            RemoveActiveOnButton();
            LinkButton6.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button7 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton7Click(object sender, EventArgs e)
        {
            FilterDirectorates(CheckBoxIncludeInactive.Checked, "STUV");
            RemoveActiveOnButton();
            LinkButton7.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button8 C lick.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton8Click(object sender, EventArgs e)
        {
            FilterDirectorates(CheckBoxIncludeInactive.Checked, "WXYZ");
            RemoveActiveOnButton();
            LinkButton8.CssClass = "button-active";
        }
        /// <summary>
        /// Buttons the create click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonCreateClick(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] != null)
            {
                int organizationId = int.Parse(Request.QueryString["id"], _formatProvider);
                Response.Redirect("DirectorateDetails.aspx?mode=create&OrganizationId=" + organizationId);
            }

        }
        /// <summary>
        /// Marks the activated.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param>
        protected void MarkActivated(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
        {

            var hId = (HiddenField)RepeaterDirectorate.Items[e.Item.ItemIndex].FindControl("HiddenDirectorateId");
            string[] values = hId.Value.Split('$');
            if (e.CommandName == "update")
            {
                int id = int.Parse(values[0], _formatProvider);
                _directorateBus = new DirectorateBus();
                _directorateBus.MakeDirectorateIsActive(id);
                Response.Redirect("DirectorateDetails.aspx?id=" + values[0] + "&mode=edit" + "&OrganizationId=" + values[1]);

            }
            else
            {
                //Response.Redirect("acb.aspx");
                Response.Redirect("DirectorateDetails.aspx?id=" + values[0] + "&mode=edit" + "&OrganizationId=" + values[1]);
            }
        }
        protected void LinkButtonDepartmentNameClick(object sender, EventArgs e)
        {
            Sorting("DirectorateName");
        }
        protected void LinkButtonAddressClick(object sender, EventArgs e)
        {
            Sorting("AddressLine1");
        }
        protected void LinkButtonPostcodeClick(object sender, EventArgs e)
        {
            Sorting("Postcode");
        }
        protected void LinkButtonContactNameClick(object sender, EventArgs e)
        {
            Sorting("ContactName");
        }
        protected void LinkButtonStatusClick(object sender, EventArgs e)
        {
            Sorting("Status");   
        }
        /// <summary>
        /// Removes the active on button.
        /// </summary>
        private void RemoveActiveOnButton()
        {
            LinkButton1.CssClass = "button-in-active";
            LinkButton2.CssClass = "button-in-active";
            LinkButton3.CssClass = "button-in-active";
            LinkButton4.CssClass = "button-in-active";
            LinkButton5.CssClass = "button-in-active";
            LinkButton6.CssClass = "button-in-active";
            LinkButton7.CssClass = "button-in-active";
            LinkButton8.CssClass = "button-in-active";
        }

        #endregion
    }
}